package com.lineage.server.command.executor;

import com.lineage.server.WriteLogTxt;
import com.lineage.server.datatables.ItemTable;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_SystemMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1Item;
import com.lineage.server.world.World;
import java.util.StringTokenizer;

public class L1DeleteItem implements L1CommandExecutor {
  public static L1CommandExecutor getInstance() {
    return new L1DeleteItem();
  }
  
  public void execute(L1PcInstance pc, String cmdName, String arg) {
    try {
      StringTokenizer st = new StringTokenizer(arg);
      String name = st.nextToken();
      String nameid = st.nextToken();
      L1PcInstance target = World.get().getPlayer(name);
      if (target == null) {
        pc.sendPackets((ServerBasePacket)new S_SystemMessage(String.valueOf(name) + "不在线或者不存在。"));
        return;
      } 
      int count = 1;
      if (st.hasMoreTokens())
        count = Integer.parseInt(st.nextToken()); 
      int itemid = 0;
      try {
        itemid = Integer.parseInt(nameid);
      } catch (NumberFormatException e) {
        itemid = ItemTable.get().findItemIdByNameWithoutSpace(
            nameid);
        if (itemid == 0) {
          pc.sendPackets((ServerBasePacket)new S_SystemMessage("找不到符合条件项目。"));
          return;
        } 
      } 
      L1Item temp = ItemTable.get().getTemplate(itemid);
      if (temp != null) {
        if (temp.isStackable()) {
          L1ItemInstance item = ItemTable.get().createItem(
              itemid);
          item.setCount(count);
          if (target.getInventory().consumeItem(item.getItemId(), count)) {
            pc.sendPackets((ServerBasePacket)new S_SystemMessage("删除" + item.getLogName() + "成功(itemid:" + itemid + ")！"));
            WriteLogTxt.Recording("删除记录", "在线删除玩家 " + target.getName() + " 道具:" + item.getLogName() + "OBJID：" + item.getId());
          } 
        } else {
          L1ItemInstance item = null;
          for (int createCount = 0; createCount < count; ) {
            item = ItemTable.get().createItem(itemid);
            if (target.getInventory().consumeItem(item.getItemId(), count)) {
              pc.sendPackets((ServerBasePacket)new S_SystemMessage("删除" + item.getLogName() + "成功(itemid:" + itemid + ")！"));
              WriteLogTxt.Recording("删除记录", "在线删除玩家 " + target.getName() + " 道具:" + item.getLogName() + "OBJID：" + item.getId());
              createCount++;
            } 
            break;
          } 
        } 
      } else {
        pc.sendPackets((ServerBasePacket)new S_SystemMessage("指定的道具编号不存在"));
      } 
    } catch (Exception e) {
      pc.sendPackets((ServerBasePacket)new S_SystemMessage(
            ".deleteitem 角色  itemid|name [数目] 请输入。"));
    } 
  }
}
